package com.ansatsing.juc.semaphore;

import java.util.concurrent.Semaphore;

/**
 * 操场类：有5个跑道
 * @auth sunyq
 * @date 2018/2/11
 **/
public class Playground {
    class Track{
        private  int trackNo;//第几跑道
        private volatile boolean useState = false;

        public Track(int trackNo) {
            this.trackNo = trackNo;
        }

        public int getTrackNo() {
            return trackNo;
        }

        public void setTrackNo(int trackNo) {
            this.trackNo = trackNo;
        }

        public boolean isUseState() {
            return useState;
        }

        public void setUseState(boolean useState) {
            this.useState = useState;
        }

        @Override
        public String toString() {
            return "Track{" +
                    "trackNo=" + trackNo +
                    ", useState=" + useState +
                    '}';
        }
    }
    private Track tracks[] = new Track[5];//5个跑道
    Semaphore semaphore = new Semaphore(5);//5个信号量【类似只有5个许可证】--控制入操场跑步人数，由于最大跑步人数为5，每人一个跑道

    public Playground(){
        for(int i=0;i<5;i++){
            tracks[i] = new Track(i+1);
        }
    }
    public Track getOneTrack(){
        Track track = null;
        try {
            semaphore.acquire();
            for(int i=0;i<5;i++){
                if(!tracks[i].useState){
                    track = tracks[i];
                    tracks[i].setUseState(true);
                    break;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return track;
    }
    public void release(int trackId){
        semaphore.release();
        tracks[trackId].useState = false;
    }
}
